// https://leetcode-cn.com/problems/symmetric-tree/submissions/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

// 法一：DFS
// class Solution {
// public:
//     bool equal(TreeNode* left, TreeNode* right) {
//         if (!left || !right) return !left && !right;
//         if (left->val != right->val) return false;
//         return equal(left->right, right->left) && equal(left->left, right->right);
//     }
//     bool isSymmetric(TreeNode* root) {
//         TreeNode* left = root->left;
//         TreeNode* right = root->right;
//         return equal(left, right);
//     }
// };

// 法二：BFS
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        queue<TreeNode*> q;
        if (!root->left && !root->right) return true; //注意
        if (!root->left || !root->right) return false;
        q.push(root->left);
        q.push(root->right);
        while (!q.empty()) {
            TreeNode* tmp1 = q.front();
            q.pop();
            TreeNode* tmp2 = q.front();
            q.pop();
            //注意这两个
            if (!tmp1 && !tmp2) continue; 
            if (!tmp1 || !tmp2) return false;
            if (tmp1->val != tmp2->val) return false;
            q.push(tmp1->left);
            q.push(tmp2->right);

            q.push(tmp1->right);
            q.push(tmp2->left);
        }
        return true;
    }
};